package edu.neusoft.springmvc.controller;

import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import edu.neusoft.springmvc.model.TestModel;

@Controller
@RequestMapping("/view")
public class TestViewController {

  @RequestMapping("/fm")
  public ModelAndView getFM() {
    ModelAndView mv = new ModelAndView();
    mv.addObject("hello", "hello world");
    mv.setViewName("freemarker");
    return mv;
  }

  @RequestMapping("/htmlview")
  public void HtmlView(Writer writer) {
    StringBuffer sb = new StringBuffer();
    sb.append("<!doctype html>");
    sb.append("<html>");
    sb.append("<head><title>this is a new page</title></head>");
    sb.append("<body><p>hello world</p></body>");
    sb.append("</html>");
    try {
      writer.write(sb.toString());
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        writer.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }

  @ModelAttribute("testModel")
  public TestModel getTestModel() {
    return new TestModel("111", "222", "333", "4");
  }

  /*  @RequestMapping("jsonview")
  public void JsonView(ModelMap modelmap, PrintWriter writer) {
  
    TestModel testmodel = (TestModel) modelmap.get("testModel");
    Map<String, Object> map = new HashMap<String, Object>();
    if (testmodel != null) {
      map.put("result", "ok");
      map.put("data", testmodel);
    }
    writer.write(JSON.toJSONString(map));
  
  }*/

  @RequestMapping("jsonview")
  @ResponseBody
  public Map<String, Object> JsonView(ModelMap modelmap) {

    TestModel testmodel = (TestModel) modelmap.get("testModel");
    Map<String, Object> map = new HashMap<String, Object>();
    if (testmodel != null) {
      map.put("result", "ok");
      map.put("data", testmodel);
    }
    return map;

  }
}
